package com.gz.im.backend.component.proxy;

import cn.hutool.json.JSONUtil;
import com.corundumstudio.socketio.SocketIOClient;
import com.gz.im.backend.callback.DefaultSendCallback;
import com.gz.im.backend.component.manage.LocalCacheManage;
import com.gz.im.backend.component.manage.RedissonManage;
import com.gz.im.backend.component.handler.RobotHandler;
import com.gz.im.backend.pojo.MessageRequest;
import com.gz.im.backend.pojo.MessageResponse;
import com.gz.im.backend.pojo.User;
import com.gz.im.backend.pojo.enums.ChatTypeEnum;
import com.gz.im.backend.pojo.enums.TurnAgentTypeEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.redisson.api.RBlockingDeque;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author GuoZhong
 * @description Im事件代理
 * @date 2023/3/28 13:43
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class ImEventProxy {

	private final RobotHandler robotHandler;

	private final LocalCacheManage localCacheManage;

	private final RedissonManage redissonManage;

	private final RocketMQTemplate rocketMQTemplate;

	/**
	 * 初始化连接
	 * @param uid
	 * @param user
	 */
	public void initOnConnect(Long uid, User user){
		//存放uid与客户端关系map
		localCacheManage.putUser(uid,user);

	}


	/**
	 * 客户对话
	 * @param messageRequest
	 */
	public void imDialog(MessageRequest messageRequest,SocketIOClient client){
		Long senderId = messageRequest.getSenderId();
		User user= localCacheManage.getUser(senderId);
		//根据转人工标识判断是否转人工 0是机器人
		if(Objects.equals(user.getTurnAgent(),TurnAgentTypeEnum.NO.getCode())){
		//匹配节点
		String speechText = robotHandler.matchNode(messageRequest);
		var response=MessageResponse.builder()
				    .ChatType(ChatTypeEnum.ROBOT.getType())
					.receiverId(senderId)
					.content(speechText)
					.time(LocalDateTime.now()).build();
		  sendMsg(response);
		}else {
			Long agentId = localCacheManage.getUserAgent(senderId);
			if (null == agentId) {
				//转人工，查询是否有空闲坐席
				RBlockingDeque<Long> agent = redissonManage.listAgentQueue();
				agentId = agent.pollLast();
				if (null == agentId) {
					log.info("坐席繁忙，请稍后等待");
				}
				localCacheManage.putUserAgent(senderId,agentId);
			}
			redissonManage.publish("topic:agent:" + agentId, messageRequest);
		}
	}
    /**
     * 发送信息
     * @param response
     */
	private void sendMsg(MessageResponse response) {
		//给IM后台端系统发送会话记录信息
		try {
			var message=MessageBuilder.withPayload(response).build();
			//rocketMQTemplate.send("topic-chat-record", message);
			rocketMQTemplate.asyncSend("topic-chat-record", message, new DefaultSendCallback());

		}catch (Exception e){
			log.error("mq send is error",e);
		}


		User user = localCacheManage.getUser(response.getReceiverId());
		user.getClient().sendEvent("chat", JSONUtil.toJsonStr(response));
	}
	/**
	 * 初始化断开连接
	 * @param uid
	 */
	public void initOnDisconnect(Long uid){
		localCacheManage.rmUser(uid);
		localCacheManage.rmUserAgent(uid);
	}

}
